package demo1;



class TreeNode {
     int val;
    TreeNode left;
     TreeNode right;
    TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
          this.right = right;
    }
 }

class Solution {
    
    public void treeToString (TreeNode t, StringBuilder sb) {
        if (t == null) {
            return ;
        }
        sb.append(t.val);
        if (t.left != null) {
            sb.append("(");
            treeToString(t.left,sb);
            sb.append(")");
        } else {
            if (t.right == null) {
                return;
            } else {
                sb.append("()");
            }
        }
        if (t.right == null) {
            return;
        } else {
            sb.append("(");
            treeToString(t.right,sb);
            sb.append(")");
        }
    }
    public String tree2str(TreeNode root) {
        if (root == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        treeToString(root,stringBuilder);
        return stringBuilder.toString();
    }
}